import { Button, Card, Form, Input, message, Modal, Table } from 'antd'
import moment from 'moment'
import React, { Component, Fragment } from 'react'
import { getrole, addrole, updaterole } from '../../api';
import FormJurisdiction from './form-jurisdiction'
import storageUtils from '../../utils/storageUtils'
import memoryUtils from '../../utils/memoryUtils';
const Item = Form.Item
export default class index extends Component {
  state = {
    visible: 0,
    role: [],
    dataSource: []
  }
  fromRef = React.createRef()
  columns = [
    {
      title: '角色名称',
      dataIndex: 'name',
      width: '20%'
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      width: '30%',
      render: value => value === undefined ? value : moment(value).format('YYYY年M月DD日 HH:mm:ss')
    },
    {
      title: '授权时间',
      dataIndex: 'auth_time',
      width: '30%',
      render: value => value === undefined ? value : moment(value).format('YYYY年M月DD日 HH:mm:ss')
    },
    {
      title: '授权人',
      dataIndex: 'auth_name',
      width: '10%'
    },
  ];
  onChange = (record, selected, selectedRows, nativeEvent) => {
    this.setState({ role: selected[0] })
  }
  onRow = (role) => {
    return {
      onClick: event => {
        this.setState({ role })
      }
    }
  }
  updaterole = async () => {
    const { role, dataSource } = this.state
    const user = storageUtils.getUser()
    const menus = this.fromRef.current.state.checkedKeys
    role.menus = menus
    role.auth_time = Date.now()
    role.auth_name=user.username
    const result = await updaterole(role)
    if (result.status === 0) {
      
      if (role._id === memoryUtils.user.role_id) {
        message.loading('当前用户权限更新，请重新登录！', 0.6)
    setTimeout(() => {
      memoryUtils.user = {}
      storageUtils.removeUser()
      this.props.history.replace('/login')
    }, 500);
      } else {
        message.success('更新成功！')
        this.setState({ dataSource: [...dataSource], visible: 0 })
      }
    }
  }
  onFinish = async (values) => {
    const result = await addrole(values.name)
    if (result.status === 0) {
      message.success('添加成功！')
      this.setState({ dataSource: [...this.state.dataSource, result.data], visible: 0 })
    }
  }
  handleCancel = () => {
    this.setState({ visible: 0 })
  }
  async componentDidMount() {
    const result = await getrole()
    if (result.status === 0) {
      this.setState({ dataSource: result.data })
    }
  }

  render() {
    const { dataSource, visible, role } = this.state
    const title = (<Fragment>
      <Button type='primary' onClick={() => { this.setState({ visible: 1 }) }}>创建角色</Button>
      <Button type='primary' style={{ marginLeft: '5px' }} disabled={!role._id}
        onClick={() => { this.setState({ visible: 2 }) }}>设置角色权限</Button>
    </Fragment>)
    return (
      <Card title={title}>
        <Table bordered
          onRow={this.onRow}
          pagination={{
            responsive: false, defaultPageSize: 9,
            showQuickJumper: { goButton: (<Fragment>&nbsp;&nbsp;<Button type='primary'>跳转</Button></Fragment>) }
          }}
          rowSelection={{ type: 'radio', selectedRowKeys: [role._id], onChange: this.onChange }}
          columns={this.columns}
          rowKey='_id'
          dataSource={dataSource}
        >
        </Table>
        <Modal title='创建角色' visible={visible === 1}
          footer={false}
          onCancel={this.handleCancel} destroyOnClose>
          <Form name="normal_login" preserve={false} onFinish={this.onFinish}>
            <Item name='name' rules={[{ required: true, message: '名称必须填写！' }]}>
              <Input placeholder='请输入角色名称' />
            </Item>
            <Item>
              <Button
                type='primary' htmlType='submit' block>提交</Button>
            </Item>
          </Form>
        </Modal>
        <Modal title='设置角色权限' visible={visible === 2} destroyOnClose
          onCancel={this.handleCancel} onOk={this.updaterole}>
          <Item>角色名称：
           <Input value={role.name} disabled />
          </Item>
          <Item>角色权限:
           <FormJurisdiction role={role} ref={this.fromRef} />
          </Item>
        </Modal>
      </Card>
    )
  }
}
